import React, { useState } from 'react';
import { Form, Button } from 'antd';
import { initFilter, getFormItem } from '../utils';
import {
   SearchOutlined,
   ReloadOutlined,
} from '@ant-design/icons';



/**
 * config例子
    [
      {
         name: 'program_name_like',
         label: '节目名称',
         type: 'string'
      },
      {
         name: ['play_start_date', 'play_stop_date'],
         label: ['开始日期', '结束日期'],
         type: 'dateRange'
      }
    ]
 */

const useFilter = (config = []) => {
    const [filter, setFilter] = useState(initFilter(config));
    const [refresh, setRefresh] = useState(false);
 
    // 重置
    const handleResetFilter = () => {
       setFilter(initFilter(config));
       setRefresh(!refresh);
    };
 
    // 修改日期
    const handleDateChange = ([startField, endField], [startTime, endTime]) => {
       setFilter({ ...filter, [startField]: startTime, [endField]: endTime });
    };
 
    // 修改输入内容
    const handleInputChange = (e) => {
       const { name, value } = e.target;
       setFilter({ ...filter, [name]: value });
    };
 
    // 修改选择器内容
    const handleSelectChange = (name, value) => {
       setFilter({ ...filter, [name]: value });
    };
 
    const FormItemEles = getFormItem(config, {
       filter,
       handleInputChange,
       handleSelectChange,
       handleDateChange,
    });
    const handleSearch = () => {
       setRefresh(!refresh); // 通知查询
    };
 
    const HandlerEles = [
       <Form.Item key="search">
          <Button
             type="primary"
             size="small"
             onClick={handleSearch}
             icon={<SearchOutlined />}
          >
             查询
          </Button>
       </Form.Item>,
       <Form.Item key="reset">
          <Button
             type="primary"
             size="small"
             onClick={handleResetFilter}
             icon={<ReloadOutlined />}
          >
             重置
          </Button>
       </Form.Item>,
    ];
 
    return {
       filter,
       FilterEles: [...FormItemEles, ...HandlerEles],
       filterRefresh: refresh,
    };
 };

 export default useFilter